<?php

// Copyright 2019 Hackware SpA <human@hackware.cl>
// "Hackware Web Services Core" is released under the MIT License terms.

namespace Hawese\Tests;

use Hawese\Core\Mailer;

class MailerTest extends TestCase
{
    public function setUp(): void
    {
        parent::setUp();

        config([
            'mail.from_address' => 'from@example.com',
            'mail.from_name' => 'From Name',
            'mail.reply_to_address' => 'reply@example.com',
            'mail.reply_to_name' => 'Reply Name',
        ]);
    }

    private function mailerInstance() {
        $mailer = app(Mailer::class);
        $mailer->CharSet = Mailer::CHARSET_UTF8;
        $mailer->addAddress('to_mail@example.com', 'Example To');
        $mailer->Subject = 'Example subject';
        $mailer->Body = '<p>Example body</p>';
        $mailer->AltBody = 'Example body';
        return $mailer;
    }

    public function testSend()
    {
        $mailer = $this->mailerInstance();
        $this->assertTrue($mailer->send());
        $this->assertStringContainsString(
            'Example body',
            $mailer->getSentMIMEMessage()
        );
    }

    public function testJsonSerialize()
    {
        $mailer = $this->mailerInstance();
        $this->assertJsonStringEqualsJsonString(
            json_encode([
                'From' => $mailer->From,
                'FromName' => $mailer->FromName,
                'Subject' => $mailer->Subject,
                'To' => [['t*****l@example.com', 'Example To']]
            ]),
            json_encode($mailer)
        );
    }

    // MailerServiceProvider tests

    public function testMailerServiceProviderSmtp()
    {
        config([
            'mail.driver' => 'smtp',
            'mail.host' => 'example.com',
            'mail.port' => 25,
            'mail.username' => 'username',
            'mail.password' => 'password',
            'mail.encryption' => 'ssl',
        ]);

        $mailer = $this->mailerInstance();

        $this->assertSame('smtp', $mailer->Mailer);
        $this->assertSame('example.com', $mailer->Host);
        $this->assertSame(25, $mailer->Port);
        $this->assertSame('username', $mailer->Username);
        $this->assertSame('password', $mailer->Password);
        $this->assertSame('ssl', $mailer->SMTPSecure);
    }

    public function testMailerServiceProviderSendmail()
    {
        config(['mail.driver' => 'sendmail']);
        $mailer = $this->mailerInstance();
        $this->assertSame('sendmail', $mailer->Mailer);
    }

    public function testMailerServiceProviderDefault()
    {
        config(['mail.driver' => 'anything']);
        $mailer = $this->mailerInstance();
        $this->assertSame('mail', $mailer->Mailer);
    }
}
